package bysj.dao;

import bysj.domain.*;
import util.JdbcHelper;

import java.sql.*;

public class ApplicationForSupervisorDao {
    private static ApplicationForSupervisorDao applicationForSupervisorDao = null;


    private ApplicationForSupervisorDao() {
    }

    public static ApplicationForSupervisorDao getInstance() {
        if(applicationForSupervisorDao ==null){
            applicationForSupervisorDao = new ApplicationForSupervisorDao();
        }
        return applicationForSupervisorDao;
    }

    public boolean add(ApplicationForSupervisor applicationForSupervisor, Connection connection) throws SQLException {
        //创建预编译对象
        PreparedStatement preparedStatement = connection.prepareStatement("Insert into applicationForSupervisor(selfIntroduction,student_id,year) Values " + "(?,?,?)", Statement.RETURN_GENERATED_KEYS);
        //为预编译对象赋值
        preparedStatement.setString(1,applicationForSupervisor.getSelfIntroduction());
        preparedStatement.setInt(2, applicationForSupervisor.getStudent().getId());
        preparedStatement.setInt(3, applicationForSupervisor.getYear());
        //执行预编译对象的executeUpdate方法，获得增加的记录行数
        int idOfAddedApplicationForSupervisor = 0;
        int rowAdd = preparedStatement.executeUpdate();
        //获取新增对象id并为applicationForSupervisor赋值
        ResultSet resultSet = preparedStatement.getGeneratedKeys();
        if (resultSet.next()) {
            //读取第一个
            idOfAddedApplicationForSupervisor = resultSet.getInt(1);
            applicationForSupervisor.setId(idOfAddedApplicationForSupervisor);
        }
        //关闭两个资源
        JdbcHelper.close(preparedStatement);
        PreparedStatement pstmt = connection.prepareStatement("Insert into applicationForSupervisorEntry(priority,teacher_id,applicationForSupervisor_id) Values " + "(?,?,?)");
        for(ApplicationForSupervisorEntry applicationForSupervisorEntry:applicationForSupervisor.getApplicationForSupervisorEntries()){
            pstmt.setInt(1,applicationForSupervisorEntry.getPriority());
            pstmt.setInt(2,applicationForSupervisorEntry.getTeacher().getId());
            pstmt.setInt(3,idOfAddedApplicationForSupervisor);
            int affectedRowNum = pstmt.executeUpdate();
        }
        JdbcHelper.close(pstmt);
        return rowAdd > 0;
    }

}
